/*
 * @lc app=leetcode.cn id=594 lang=cpp
 *
 * [594] 最长和谐子序列
 */

#include <limits.h>

#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;

// @lc code=start
class Solution {
   public:
    int findLHS(vector<int>& nums) {
        int result = 0;
        int n = nums.size();
        set<int> number;
        map<int, int> count;

        // 遍历原数组，记录出现的数字和每个数字出现的次数
        for (int num : nums) {
            number.insert(num);
            if (count.count(num) > 0) {
                count[num] = count[num] + 1;
            } else {
                count.insert(pair<int, int>(num, 1));
            }
        }

        // 遍历集合，寻找相邻数字出现次数之和最大的值
        for (int num : number) {
            if (count.count(num + 1) > 0) {
                if (count[num] + count[num + 1] > result) {
                    result = count[num] + count[num + 1];
                }
            }
        }

        return result;
    }
};
// @lc code=end
